<template>
  <a-modal :visible="visible" @cancel="cancel" @ok="submitData">
    <template #title>
      {{ opType === 1 ? GLang.EDIT : GLang.ADD }}
    </template>
    <div class="content">
      <a-form :model="formData">
        <a-form-item field="code" :label="lang.PLACEHOLDER_TRE">
          <a-input v-model="formData.code" />
        </a-form-item>
        <a-form-item field="name" :label="lang.PLACEHOLDER_TWO">
          <a-input v-model="formData.name" />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { defineEmits, defineProps, ref, watch } from 'vue';
  import { getLang } from '@/hooks/lang';
  import { Message } from '@arco-design/web-vue';
  import { addModule, editModule } from './api';
  import { LangModule } from './lang-module';

  const GLang = getLang('G_Operate');
  const Props = defineProps({
    visible: Boolean,
    opType: {
      type: Number,
      default: 0, // 0 表示新增  1 表示编辑
    },
    currentModule: Object,
    lang: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });
  const emits = defineEmits(['update:visible', 'add', 'edit']);

  const formData = ref<LangModule>({
    code: '',
    name: '',
  });
  const addLangModule = () => {
    const params: LangModule = {
      code: formData.value.code,
      name: formData.value.name,
    };
    addModule(params).then((res: any) => {
      if (res.code === 8000000) {
        Message.success('新增成功');
        emits('add');
        emits('update:visible', false);
      }
    });
  };
  const editLangModule = () => {
    const params: LangModule = {
      code: formData.value.code,
      name: formData.value.name,
      id: Props.currentModule?.id,
    };
    editModule(params).then((res: any) => {
      if (res.code === 8000000) {
        Message.success('修改成功');
        emits('edit');
        emits('update:visible', false);
      }
    });
  };
  const cancel = () => {
    emits('update:visible', false);
    formData.value = {
      code: '',
      name: '',
    };
  };
  const submitData = () => {
    if (Props.opType === 1) {
      editLangModule();
      // emits('edit', )
    } else {
      addLangModule();
    }
    // formData.value = {
    //   code: '',
    //   name: ''
    // };
  };

  watch(
    () => Props.opType,
    (newValue) => {
      if (newValue === 1) {
        const module: { code: string; name: string; id?: number } = JSON.parse(
          JSON.stringify(Props.currentModule)
        );
        formData.value = JSON.parse(JSON.stringify(Props.currentModule));
      }
    }
  );
</script>

<style scoped></style>